/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/

/**
 *
 * $Id: TextServer.hpp,v 1.5 2009-05-13 07:18:19 amaula Exp $
 *
 * \file
 * \brief MaCI - Text Server interface
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 */
#ifndef _MACI_INTERFACE_TEXTSERVER_HPP_
#define _MACI_INTERFACE_TEXTSERVER_HPP_

#include "MaCI.hpp"
#include "TextData.hpp"
#include "thread.hpp"
#include "sync.hpp"
#include <list>

// Forward declare gimi::GIMI
namespace gimi {
  class GIMI;
  class GIMIMessage;
}


namespace MaCI{
  namespace Text{
   
    /** MaCI - Text Server interface
     * 
     * This class contains the methods and types for providing
     * the Text service in the GIMnet.
     */
    class CTextServer : public MaCI::CMaCI,
                        private gim::CThread,
                        private gim::CSync
    {
    public:
      /** Constructor.
       * 
       * Constructor of the TextServer. This requires;
       * a pointer to Initialized and connected GIMI, minor
       * number of this interface (Used as GIMI minor number)
       *
       * @param[in] aMaCICtrlServerPtr Pointer to MaCICtrlServer.
       * @param[in] aInterfaceMinor Interface minor number. Usually
       * used to indicate the instance of devices of same type.
       */
      CTextServer(MaCICtrl::CMaCICtrlServer *aMaCICtrlServerPtr, const int aInterfaceMinor);

      /** Destructor.
       */
      ~CTextServer();

      /** Opens Text Server 
       *
       * Opens the Text Server,  basicly registers device to GIMI.
       *  
       * @return                Returns a value of type EMaCIError. 
       *                        
       * \see EMaCIError
       */
      MaCI::EMaCIError DoOpen(void);

      /** Close device.
       *
       * Closes the TextServer. Closes all GIMI registrations and queues.
       *
       * @return                Returns a value of type EMaCIError.
       *
       * \see EMaCIError
       */
      MaCI::EMaCIError DoClose(void);

      /** Wait for a Command.
       *
       * This function waits until new command arrives or timeout occurs.
       * If there is unhandled commands since last read, the next
       * in queue is returned. If you want to clear the queue between calls,
       * use ClearCommandBuffer() function.
       *
       * When a command is succesfully returned, the user can inspect
       * the current command through the GetCommand() call of
       * class CTextData. Then, according to command and its
       * specification, additional datafields may be present, they
       * can be queried by similar Get... functions. See the 
       * description of the data encoder/decoder module CTextData.
       *
       * 
       * \see ClearCommandBuffer()
       * \see CTextData
       * \see MaCI::EMaCIError
       * 
       * @param[out] aData      Reference to TextData. This will
       *                        be filled with incoming command when
       *                        this call is completed succesfully.
       * @param[out] aInfo      Reference to replyInfo. Use this replyInfo 
       *                        to SendReply-function when you have to send 
       *                        a Reply.
       * @param[in] aTimeout_ms Timeout to wait until operation fails
       *                        for timeout.
       * @param[in] aSkipQueued If this value is set to 'true', the
       *                        function will only return the last
       *                        received command and pop older ones
       *                        out from the queue. If this is set to
       *                        'false', all commands are received in
       *                        order. If parameter is undefined, 
       *                        default is 'false'.
       * @return                'KMaCIOK'  when succesfully received
       *                        a new command. KMaCITimeout when operation
       *                        timed out before a command was received.
       *                        Other errors returned when appropriate.
       *                        (See the MaCI::EMaCIError for description)
       * \see EMaCIError
       */
      MaCI::EMaCIError WaitCommand(CTextData &aData,
                                   TReplyInfo &aInfo,
                                   const unsigned int aTimeout_ms,
                                   bool aSkipQueued = false);
      
      /** Send text to clients.
       *
       * This function sends wanted text string to all text-clients.
       *
       * @param[in] aText             Text to send
       * @return                      True if succeeded, false if failed(timeout, no connection..)
       */
      bool SendText(const std::string &aText);

      /**
       * Sends text accomplished message to client. To be used when 
       * e.g. text is spoken at server or displayed to screen. 
       *
       * @param[in] aText       Reference to accomplished text string
       * @param[in] aInfo       Reference to reply info. Get this replyInfo from WaitCommand.
       *
       * @return                'KMaCIOK' when reply message succesfully sent.
       *                        Other errors returned when appropriate.
       *                        (See the MaCI::EMaCIError for description)
       * \see EMaCIError
       */
      bool SendTextAccomplishedMessage(const std::string &aText,
                                       TReplyInfo &aInfo);

      /** Clear the incoming commands buffer.
       *
       * This functions clears the accumulated command buffer. This
       * function call may be required if the server for some 
       * reason wants to skip unprocessed commands. Per default the incoming
       * 'Set' commands are all queued until processed. (This ensures
       * that critical commands don't get lost)
       */
      void ClearCommandBuffer(void);

    private:
      int ThreadFunction(const int aThreadNumber); ///< Incoming data handler function
      int ProcessMessage(const gimi::GIMIMessage &msg); ///< Incoming data processor function
      volatile bool iServerActive; ///< Flag indicating whether the server is active.
      std::list<const CTextData *> iTextCommandArray; ///< Array of unprocessed commands.
      std::list<const TReplyInfo *> iReplyDataArray; ///< Array of unprocessed commands.
    };

  }

}

#endif ///<_MACI_INTERFACE_TEXTSERVER_HPP_
